<template>
  <view>
    <u-popup mode="left" :show="show" @close="close" :safeAreaInsetBottom="true" :round="10">
      <view class="broadside-container">

        <!-- 用户信息区域 -->
        <view class="user-info-area">
          <view class="avatar-wrap">
            <u-avatar size="50" :src="userInfo.headImage || userInfo.memberNumber"></u-avatar>
          </view>
          <view v-if="isLogin" class="user-info-content">
            <view class="user-name">{{ userInfo.memberName || '会员用户' }}</view>
            <view class="user-id">ID: {{ userInfo.id || '' }}</view>
          </view>
          <view v-else class="user-info-content" @click="goToLogin">
            <view class="user-name">未登录</view>
            <view class="user-id">点击登录账号</view>
          </view>
          <view class="setting-icon" @click="goToSettings">
            <u-icon name="setting" color="#999" size="24"></u-icon>
          </view>
        </view>
        <view class="header">
          <view class="title">对话记录</view>
          <view class="new-chat-btn" @click="createNewSession">
            <u-icon name="plus-circle" color="#2979ff" size="20"></u-icon>
            <text>新对话</text>
          </view>
        </view>

        <!-- 使用scroll-view替代mescroll-body -->
        <scroll-view
          scroll-y
          style="height: calc(100vh - 100px)"
          @scrolltolower="loadMore"
          refresher-enabled
          :refresher-triggered="isRefreshing"
          @refresherrefresh="onRefresh"
          :scroll-with-animation="true"
          :lower-threshold="50">
          <view class="chat-list">
            <view
                class="chat-item"
                v-for="(item, index) in chatList"
                :key="index"
                @click="selectSession(item)">
              <view class="chat-content">{{ item.name || item.content }}</view>
              <view class="chat-date">{{ formatDate(item.update_time) }}</view>
            </view>
            <view class="loading-more" v-if="loading">
              <text>加载中...</text>
            </view>
            <view class="no-more" v-if="noMore">没有更多了</view>
          </view>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  name: "broadside",
  props: {
    show: {
      type: Boolean,
      default: false
    },
    apiUrl: {
      type: String,
      default: ''
    },
    apiKey: {
      type: String,
      default: ''
    },
    chatId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chatList: [],
      currentPage: 1,
      pageSize: 30,
      loading: false,
      noMore: false,
      isRefreshing: false,
      userInfo: {}, // 用户信息
      isLogin: false // 登录状态
    }
  },
  computed: {
    // 从store获取用户信息
    storeUserInfo() {
      return this.$store.state.userInfo || {};
    }
  },
  watch: {
    // 监听store中用户信息变化
    storeUserInfo: {
      handler(newVal) {
        if (newVal && newVal.token) {
          this.userInfo = newVal;
          this.isLogin = true;
        } else {
          this.isLogin = false;
        }
      },
      immediate: true
    }
  },
  methods: {
    close() {
      this.$emit("update:show", false)
    },

    // 跳转到登录页面
    goToLogin() {
      uni.navigateTo({
        url: '/pages/user/login'
      });
      this.close();
    },

    // 跳转到设置页面
    goToSettings() {
      uni.navigateTo({
        url: '/pages/my/set/index'
      });
      this.close();
    },

    // 创建新会话
    createNewSession() {
      this.$emit("newSession");
      this.close();
    },

    // 选择会话
    selectSession(session) {
      this.$emit("select", session);
      this.close();
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      this.currentPage = 1;
      this.noMore = false;
      await this.loadSessions(this.currentPage, this.pageSize);
      this.isRefreshing = false; // 这里已经设置了
    },

    // 上拉加载更多
    async loadMore() {

    /*  if (this.loading || this.noMore) return;*/
      this.loading = true;
      try {

        this.currentPage++;
        await this.loadSessions(this.currentPage, this.pageSize);
      } finally {
        this.loading = false;
      }
    },

    // 加载会话列表
    async loadSessions(pageNum, pageSize) {
      if (this.loading && this.isRefreshing) return;
      this.loading = true;

      try {
        const response = await uni.request({
          url: `${this.apiUrl}/api/v1/chats/${this.chatId}/sessions`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${this.apiKey}`
          },
          data: {
            chat_id: this.chatId,
            page: pageNum,
            page_size: pageSize,
            desc: true,
            user_id: this.$store.state.userInfo.id || ''
          }
        });

        const res = response[1].data;
        if (res.code === 0) {
          const list = res.data || [];

          if (pageNum === 1) {
            this.chatList = list;
          } else {
            this.chatList = [...this.chatList, ...list];
          }

          // 判断是否还有更多数据
          this.noMore = list.length <= pageSize;
        }
      } catch (error) {
        console.error('加载会话列表出错:', error);
        if (pageNum > 1) this.currentPage--; // 回滚页码
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        if (this.isRefreshing) {
          this.isRefreshing = false;
        }
      }
    }
  },
  mounted() {
    this.loadSessions(1, this.pageSize);
  }
}
</script>

<style scoped lang="scss">
/* 新增加载样式 */
.loading-more, .no-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 26rpx;
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;

  text {
    margin-left: 10rpx;
  }
}

/* 其他样式保持不变 */
.broadside-container {
  width: 600rpx;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}

/* 用户信息区域样式 */
.user-info-area {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #edf0f7;
  background-color: #f0f7f7; /* 调整为与主题色相协调的浅色背景 */
  border-radius: 12rpx;
  margin: 15rpx;
  box-shadow: 0 2rpx 8rpx rgba(14, 156, 152, 0.08); /* 调整阴影颜色与主题色相协调 */
  transition: all 0.3s ease;
}

.avatar-wrap {
  margin-right: 20rpx;
}

.user-info-content {
  flex: 1;
}

.user-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-bottom: 5rpx;
}

.user-id {
  font-size: 12px;
  color: #999;
}

.setting-icon {
  padding: 10rpx;
}

.header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f2f2f2;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.new-chat-btn {
  display: flex;
  align-items: center;
  background-color: #ecf5ff;
  padding: 5px 10px;
  border-radius: 16px;

  text {
    font-size: 14px;
    color: #2979ff;
    margin-left: 4px;
  }
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: space-between;

  &:active {
    background-color: #f8f8f8;
  }
}

.chat-content {
  font-size: 15px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  flex: 1;
}

.chat-date {
  font-size: 12px;
  color: #aaa;
  margin-left: 10px;
  flex-shrink: 0;
}
</style>
